package me.illtamer.rpc.transport.socket.server;

import me.illtamer.rpc.entity.RpcRequest;
import me.illtamer.rpc.handler.RequestHandler;
import me.illtamer.rpc.transport.socket.util.ObjectReader;
import me.illtamer.rpc.transport.socket.util.ObjectWriter;
import me.illtamer.serializer.CommonSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * IO 传输模式 | 处理客户端 RpcRequest 的工作线程
 * */
public class SocketRequestHandlerThread implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(SocketRequestHandlerThread.class);

    private final Socket socket;
    private final RequestHandler requestHandler;
    private final CommonSerializer serializer;

    public SocketRequestHandlerThread(Socket socket, RequestHandler requestHandler, CommonSerializer serializer) {
        this.socket = socket;
        this.requestHandler = requestHandler;
        this.serializer = serializer;
    }

    @SuppressWarnings("all")
    @Override
    public void run() {
        try (
                InputStream input = socket.getInputStream();
                OutputStream output = socket.getOutputStream();
        ) {
            RpcRequest rpcRequest = (RpcRequest) ObjectReader.readObject(input);
            Object response = requestHandler.handle(rpcRequest);
            ObjectWriter.writeObject(output, response, serializer);
        } catch (IOException e) {
            logger.error("调用或发送时发生错误：", e);
        }
    }

}
